package Thread;

class MyBlockingQueue<E>{
    //自己实现阻塞队列
    //有take和put
    private Object object = new Object();
  volatile private E[] array = (E[]) new Object[50];
  volatile private   int first = 0;
   volatile private int last = 0;

    //先进先出
    //循环队列
    //预留一个用来判断是满还是空的内存
    //first == last是空
    //(last+1)%array.length == first 是满
    //出队列
    public E take() throws InterruptedException {
        synchronized (this){
            //如果是空就wait
            while(first == last){
                System.out.println("队列空了");
                this.wait();
            }
            E value = array[first];
            first = (first+1)%array.length;//(49+1)%50=0
                //唤醒进队列
            this.notify();
            return value;

        }
    }
    //进队列
 public void put(E value) throws InterruptedException {
        synchronized (this){
            while((last+1)%array.length == first){
                System.out.println("队列满了");
                this.wait();
            }
            array[last] = value;
            last = (last+1)%array.length;//(49+1)%50 == 0
            //释放
                this.notify();
        }

    }

}
public class ThreadDemo18 {
    public static void main(String[] args) {
        MyBlockingQueue<Integer> deque = new MyBlockingQueue<Integer>();
        //消费者
        Thread t1 = new Thread(()->{
            while (true){
                try {
                    System.out.println("消费者元素: "+deque.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        //生产者
        Thread t2 = new Thread(()->{
            int value = 0;
            while (true){
                try {
                    System.out.println("生产元素: "+value);
                    deque.put(value++);
                 //   Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}
